package com.example.sharedpreference;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    //创建的文件名
    private static final String FileName = "config";

    //Keys
    private static final String Key_UserName = "UserName";//用户名
    private static final String Key_StuNum = "StuNum";//学号
    private static final String Key_LoginDate = "LoginDate";

    SharedPreferences preferences;
    SharedPreferences.Editor editor;

    private ListView contact_view;
    private ArrayAdapter<String> cAdapter;
    private final List<String> contactList = new ArrayList<>();
    public static final int REQ_CODE_CONTACT = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获得SharedPreference实例
        preferences = getSharedPreferences(FileName, MODE_PRIVATE);
        editor = preferences.edit();

        Button btnWrite = findViewById(R.id.write);
        btnWrite.setOnClickListener(view -> {
            editor.putString(Key_UserName, "LongHaoYue");
            editor.putString(Key_StuNum, "2019011378");

            @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String strLoginDate = simpleDateFormat.format(new Date());
            editor.putString(Key_LoginDate, strLoginDate);

            editor.apply();
            Toast.makeText(MainActivity.this, "写入完成", Toast.LENGTH_SHORT).show();
        });

        Button btnRead = findViewById(R.id.read);
        btnRead.setOnClickListener(view -> {
            String UserName = preferences.getString(Key_UserName, null);
            String StuNum = preferences.getString(Key_StuNum, null);
            String LoginDate = preferences.getString(Key_LoginDate, null);
            if(UserName != null && StuNum != null){
                Toast.makeText(MainActivity.this, "用户名:"+ UserName+ "\n学号:"+ StuNum
                    + "\n登录时间:"+ LoginDate, Toast.LENGTH_LONG).show();
            }else {
                Toast.makeText(MainActivity.this, "无数据",Toast.LENGTH_LONG).show();
            }
        });


        Button btnReadContact = findViewById(R.id.readContact);
        btnReadContact.setOnClickListener(view -> {
            initView();
            initAdapter();
            checkContactPermission();
        });
    }

    private void checkContactPermission(){
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
            != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}
            , REQ_CODE_CONTACT);
        } else {
            query();
        }
    }

    private void query(){
        ContentResolver contentResolver = this.getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

        if(cursor != null){
            while(cursor.moveToNext()){
                @SuppressLint("Range")
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                @SuppressLint("Range")
                String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                contactList.add(name + "Num:"+ number);
            }
            cAdapter.notifyDataSetChanged();
            cursor.close();
        }
    }

    private void initAdapter(){
        cAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, contactList);
        contact_view.setAdapter(cAdapter);
    }
    private void initView(){
        contact_view = findViewById(R.id.contact);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[]permissions, @NonNull int[]grantResults){
        if(requestCode == REQ_CODE_CONTACT && grantResults.length > 0 &&
            grantResults[0] == PackageManager.PERMISSION_GRANTED){
            query();
        } else {
            Toast.makeText(this, "未获得联系人权限", Toast.LENGTH_SHORT).show();
        }
    }
}